<template>
  <div class="page-check">
    <header class="check-header">
      <div class="check-header-title">
        <h1>审批</h1>
        <a-divider type="vertical" />
        <h2>Check Activities</h2>
      </div>

      <div class="check-header-tool-bar">
        <div class="check-refresh-container">
          <a-button @click="onRefresh" :loading="loadingFlag.refreshLoading">
            REFRESH
          </a-button>
        </div>
        <div class="check-search-container">
          <a-input-search
            placeholder="activity name or id"
            style="width: 200px"
          />
        </div>
      </div>
    </header>
    <a-table
      :columns="columns"
      :data-source="showedActivityList"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <a slot="name" slot-scope="text">{{ text }}</a>
      <span slot="customTitle">Name</span>
      <span slot="tags" slot-scope="tags">
        <a-tag
          v-for="tag in tags"
          :key="tag"
          :color="
            tag === 'default'
              ? 'volcano'
              : tag.length > 5
              ? 'geekblue'
              : 'green'
          "
        >
          {{ tag.toUpperCase() }}
        </a-tag>
      </span>
      <span slot="action" slot-scope="text, record">
        <!-- <a @click="approve(record)">Approve</a> -->
        <span @click="confirmApprove(record)">Approve</span>
        <a-divider type="vertical" />
        <!-- <a class="ant-dropdown-link"> More actions <a-icon type="down" /> </a> -->
        <a-dropdown>
          <a class="ant-dropdown-link" @click="(e) => e.preventDefault()">
            More actions
            <a-icon type="down" />
          </a>
          <a-menu slot="overlay">
            <a-menu-item>
              <span @click="showDetail(record)">Detail</span>
            </a-menu-item>
            <a-menu-item>
              <!-- <a href="javascript:;">Deny</a> -->
              <span @click="showDeny(record)">Deny</span>
            </a-menu-item>
          </a-menu>
        </a-dropdown>
      </span>
    </a-table>

    <!-- DETAIL -->
    <a-modal
      v-model="detailVisible"
      title="Detail"
      centered
      width="80%"
      @ok="() => (detailVisible = false)"
    >
      <div class="detail-container">
        <UserInfoCard
          class="detail-user-info-card"
          title="Publisher Information"
          :avatar="GLOBAL.site + '/' + detailPublisher.avatar"
          :id="detailPublisher.id"
          :userName="detailPublisher.userName"
          :userNumber="detailPublisher.userNumber"
          :phoneNumber="detailPublisher.phoneNumber"
          :age="detailPublisher.age"
          :gender="detailPublisher.gender"
        ></UserInfoCard>
        <ActivityInfoCard
          class="detail-activity-info-card"
          title="Activity Information"
          :activityId="detailActivity.activityId"
          :activityName="detailActivity.activityName"
          :activityLocation="detailActivity.activityLocation"
          :activityEnd="detailActivity.activityEnd"
          :activityProfile="detailActivity.activityProfile"
          :activityKind="detailActivity.activityKind"
          :activityPic="GLOBAL.site + '/' + detailActivity.activityPic"
          :joinNum="detailActivity.joinNum"
          :publisherId="detailActivity.publisherId"
        ></ActivityInfoCard>
      </div>
    </a-modal>
    <!-- DENY REASON -->
    <a-modal
      v-model="denyVisiable"
      title="Deny Reason"
      centered
      @ok="confirmDeny()"
    >
      <a-textarea
        placeholder="You can input the reason which will be sent to publisher here"
        :auto-size="{ minRows: 2, maxRows: 6 }"
      />
    </a-modal>
  </div>
</template>

<script>
import RequestUtils from "../../utils/requestUtils";
import Utils from "../../utils/utils";
import UserInfoCard from "../../components/userInfoCard/userInfoCard";
import ActivityInfoCard from "../../components/activityInfoCard/activityInfoCard";

const columns = [
  {
    dataIndex: "name",
    key: "name",
    slots: { title: "customTitle" },
    scopedSlots: { customRender: "name" },
  },
  {
    dataIndex: "publisherId",
    title: "Publisher Id",
    key: "publisherId",
    // slots: { title: "customTitle" },
    scopedSlots: { customRender: "name" },
  },
  {
    title: "Start",
    dataIndex: "start",
    key: "start",
  },
  {
    title: "End",
    dataIndex: "end",
    key: "end",
  },
  {
    title: "Location",
    dataIndex: "location",
    key: "location",
  },
  {
    title: "Tags",
    key: "tags",
    dataIndex: "tags",
    scopedSlots: { customRender: "tags" },
  },
  {
    title: "Action",
    key: "action",
    scopedSlots: { customRender: "action" },
  },
];

const showedActivityList = [
  {
    key: "1",
    name: "[测试]程序设计实践",
    publisherId: "Chase",
    start: Utils.formatTime(new Date()),
    end: Utils.formatTime(new Date()),
    location: "诚园八斋",
    tags: ["project", "study"],
  },
  {
    key: "2",
    name: "[测试]LOL战斗之夜",
    publisherId: "Alex",
    start: Utils.formatTime(new Date()),
    end: Utils.formatTime(new Date()),
    location: "诚园八斋221",
    tags: ["game"],
  },
  {
    key: "3",
    name: "[测试]卷王聚会",
    publisherId: "Prokey",
    start: Utils.formatTime(new Date()),
    end: Utils.formatTime(new Date()),
    location: "郑东图书馆",
    tags: ["study", "default"],
  },
];

export default {
  name: "Check",
  data() {
    return {
      showedActivityList,
      columns,
      // For controlling deny modal
      denyVisiable: false,
      // For controlling detail modal
      detailVisible: false,
      // Activities waiting checked list
      activityList: null,
      // Current selected for denied showed activity
      // whose format is different from activity
      deniedShowedActivity: null,
      // The number of the page of activities waiting checked
      totalPages: null,
      // The account of activities waiting checked
      totalElements: null,
      loadingFlag: {
        refreshLoading: false,
      },
      pagination: {
        total: this.totalElements || 0,
        pageSize: 8,
        current: 1,
      },
      detailPublisher: {
        avatar: null,
        id: null,
        userName: null,
        userNumber: null,
        phoneNumber: null,
        age: null,
        gender: null,
      },
      detailActivity: {
        activityId: null,
        activityName: null,
        activityLocation: null,
        activityStart: null,
        activityEnd: null,
        activityProfile:
          "高级程序设计实践周日就要展示了我们还没写完要来不及了都给我加班加点的写别天天就知道在宿舍打英雄联盟有时间一起来写程设它不香吗？",
        activityKind: null,
        activityPic: null,
        joinNum: null,
        publisherId: null,
      },
    };
  },
  components: {
    UserInfoCard,
    ActivityInfoCard,
  },
  methods: {
    confirmApprove(record) {
      let that = this;
      const activityId = record.key;
      console.log(`key=${record.key} name=${record.name}`);
      that.$confirm({
        title: `Confirm to approve activity?`,
        content: `Approve [${record.name}] with key=[${record.key}]?`,
        onOk() {
          // Approve
          RequestUtils.requestCheckActivity(
            that,
            sessionStorage.getItem("id"),
            activityId,
            true,
            function (res) {
              console.log(res);
              that.$message.success("Succeed to approve");
            },
            function (res) {
              console.error(res);
              that.$message.error("批准失败，请稍后重试");
            }
          );
          that.onRefresh();
        },
        onCancel() {},
      });
    },

    /**
     * Confirm to deny, send request and hide modal
     */
    confirmDeny() {
      let that = this;
      let showedActivity = this.deniedShowedActivity;
      console.log(showedActivity);
      RequestUtils.requestCheckActivity(
        that,
        sessionStorage.getItem("id"),
        showedActivity.key,
        false,
        function (res) {
          console.log(res);
          // TO-DO: 删除该项活动，或者重新获取列表
          that.refreshShowedCheckedActivityList();
          // Hide modal
          that.denyVisiable = false;
          that.$message.success("拒绝活动成功");
        },
        function (error) {
          console.log(error);
          that.$message.error("拒绝活动失败，请稍后重试");
        }
      );
    },
    onRefresh() {
      this.loadingFlag.refreshLoading = true;
      this.refreshShowedCheckedActivityList();
    },
    /**
     * Request checked activitylist from back-end
     */
    requestCheckedActivityList(page, size, success, fail) {
      "user strict";
      let that = this;
      this.axios
        .get(
          `${that.GLOBAL.site}/admins/${sessionStorage.getItem(
            "id"
          )}/check?page=${page}&size=${size}&state=`,
          {
            headers: {
              Authorization: `Bearer:${sessionStorage.getItem("token")}`,
            },
          }
        )
        .then(function (res) {
          if (success instanceof Function) {
            success(res);
          }
        })
        .catch(function (error) {
          if (fail instanceof Function) {
            fail(error);
          }
        });
    },
    /**
     * Convert activityList derived from back-end
     * into showedActivityList formated for display.
     */
    activityList2showedActivityList() {
      if (this.activityList.length === 0) {
        return null;
      }

      let activityData = [];

      for (const key in this.activityList) {
        const activity = this.activityList[key];
        let startTime = Utils.formatTime(new Date(activity.activityStart));
        let endTime = Utils.formatTime(new Date(activity.activityEnd));
        activityData.push({
          key: activity.activityId,
          name: activity.activityName,
          publisherId: activity.publisherId,
          start: startTime,
          end: endTime,
          location: activity.activityLocation,
          tags: ["OTHER"],
        });
      }

      return activityData;
    },
    handleTableChange(e) {
      let that = this;
      const page = e.current != null ? e.current - 1 : 0;
      const size = e.pageSize;
      // Set current page to enable 'nextPage'
      this.pagination.current = e.current;
      this.requestCheckedActivityList(
        page,
        size,
        function (res) {
          console.log(res);
          if (res.status == 200) {
            // Set page info
            that.totalPages = res.data.result.totalPages;
            that.totalElements = res.data.result.totalElements;
            that.pagination.total = that.totalElements;
            
            // NEW UNDERSTANDING
            // ShowedActivityList, showed in component of ant design,
            // do not need store all records. It's for display current
            // records, while the pagination's pages does not depended on
            // the length of showedActivityList, but attribute total.
            // In the past, I thought pagination could display many pages
            // because there was too many records which can not showed in 
            // one page that restricted by attribute pageSize in the showedactivitylist.
            // So it's not necessary to repalce(using splice()) records in previous page.
            // The same applies to the refer function
            // THE UNDERSTANDING SAME APPLIES TO THE FUNCTION:
            // <code>refreshShowedCheckedActivityList()</code>

            that.activityList = res.data.result.content;

            // Replace corresponding content in activityList
            // const start = (page - 1) * size;
            // let oldCorrespondingActivityList = that.activityList.splice(
            //   start,
            //   size,
            //   ...res.data.result.content
            // );
            // console.log("replaced activity list: ");
            // console.log(oldCorrespondingActivityList);

            that.showedActivityList = that.activityList2showedActivityList();
          }
        },
        function (error) {
          console.log(error);
          that.$message.error("获取待审核活动列表失败，请稍后重试");
        }
      );
    },
    showDetail(record) {
      // Show card
      this.detailVisible = true;

      let that = this;

      // Set detailActivity for display
      this.activityList.forEach((activity) => {
        if (activity.activityId == record.key) {
          // that.detailActivity = activity;
          this.detailActivity = activity;
          return;
        }
      }, this);

      // Set detailPublisher for display
      console.log(record);
      RequestUtils.requestUserInfo(
        this,
        record.publisherId,
        (res) => {
          console.log(res);
          let data = res.data;
          // let result = data.result;
          if (data.error_code == 0) {
            // Get publisher information
            let publisher = data.result;
            this.detailPublisher = publisher;
          } else {
            that.$message.error(
              `获取发布者信息失败，error_code=${res.data.error_code}`
            );
          }
        },
        (error) => {
          console.log(error);
          that.$message.error(
            "获取发布者信息请求发送失败，RequestUtils.requestUserInfo()"
          );
        }
      );
    },
    showDeny(record) {
      this.denyVisiable = true;
      // Set deniedShowedActivity for calling of function confirmDeny()
      this.deniedShowedActivity = record;
    },
    refreshShowedCheckedActivityList() {
      let that = this;
      // Get waiting checked activities when mounted
      this.requestCheckedActivityList(
        that.pagination.current == null ? 0 : that.pagination.current - 1,
        that.pagination.pageSize,
        (res) => {
          // Success
          console.log(res);
          if (res.status == 200) {
            // Set page info
            that.totalPages = res.data.result.totalPages;
            that.totalElements = res.data.result.totalElements;
            that.pagination.total = that.totalElements;

            that.activityList = res.data.result.content;

            that.showedActivityList = that.activityList2showedActivityList();
          }
          window.setTimeout(() => {
            that.loadingFlag.refreshLoading = false;
          }, 500);
        },
        (res) => {
          // Fail
          console.log(res);
          that.$message.error("获取待审核活动列表失败，请稍后重试");
          window.setTimeout(() => {
            that.loadingFlag.refreshLoading = false;
          }, 500);
        }
      );
    },
  },
  mounted() {
    this.refreshShowedCheckedActivityList();
  },
};
</script>
<style lang="less" scoped>
.check-header {
  .check-header-title {
    display: flex;
    align-items: center;
    h1 {
      font-size: 36px;
      // margin: 10px;
    }
    h2 {
      margin: 0 0 0 20px;
    }
  }
  .check-header-tool-bar {
    margin: 0 0 20px 0;
    display: flex;

    .check-refresh-container {
      margin: 0 20px 0 0;
    }
  }
}
.detail-container {
  width: 100%;
  height: 100%;
  display: flex;
  .detail-user-info-card {
    width: 30%;
  }
  .detail-activity-info-card {
    width: 70%;
  }
}
</style>